package com.wchen.project.zk.zkclient;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;

/**
 * @Desc:   使用 ZkClient 获取子节点列表
 * @author: cww
 * @DateTime: 2020-01-20 19:06
 */

public class ZookeeperGetChildrenByZkClient {
    public static void main(String[] args) throws Exception{
        String path = "/zk-book";
        ZkClient zkClient = new ZkClient("home:2181", 5000);
        zkClient.subscribeChildChanges(path, new IZkChildListener() {
            /**
             *  注意：客户端可以对一个不存在的节点进行子节点变更监听
             * @param parentPath    父节点的节点路径
             * @param currentChilds 子节点相对路径列表，如果没有子节点，将为null
             * @throws Exception
             */
            @Override
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                System.out.println(parentPath + " 's children changed, currentChilds: " + currentChilds);
            }
        });
        // 父节点自身的创建于删除，也将进行通知客户端
        zkClient.createPersistent(path);
        Thread.sleep(1000);
        System.out.println(zkClient.getChildren(path));
        Thread.sleep(1000);
        zkClient.createPersistent(path +"/c1");
        Thread.sleep(1000);
        zkClient.delete(path + "/c1");
        Thread.sleep(1000);
        zkClient.delete(path);
        Thread.sleep(5000);
    }
}
